<template>
  <div class="user-votes">
    <el-card>
      <div slot="header" class="clearfix">
        <span>我的投票</span>
      </div>
      
      <div class="empty-block" v-if="voteList.length === 0">
        <el-empty description="暂无投票记录，快去欣赏并投票支持您喜欢的作品吧！">
          <el-button type="primary" @click="$router.push('/')">浏览作品</el-button>
        </el-empty>
      </div>
      
      <el-table
        v-else
        :data="voteList"
        style="width: 100%">
        <el-table-column
          label="作品"
          width="120">
          <template slot-scope="{row}">
            <router-link :to="`/detail/${row.photoId}`">
              <el-image 
                style="width: 80px; height: 80px"
                :src="row.photoImgUrl" 
                :preview-src-list="[row.photoImgUrl]">
              </el-image>
            </router-link>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="photoTitle"
          label="作品标题">
          <template slot-scope="{row}">
            <router-link :to="`/detail/${row.photoId}`" class="photo-title">
              {{ row.photoTitle }}
            </router-link>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="photoAuthor"
          label="作者"
          width="120">
        </el-table-column>
        
        <el-table-column
          prop="score"
          label="我的评分"
          width="100">
          <template slot-scope="{row}">
            <el-rate
              v-model="row.score"
              disabled
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
            </el-rate>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="voteTime"
          label="投票时间"
          width="180">
          <template slot-scope="{row}">
            {{ formatDate(row.voteTime) }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作"
          width="150">
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="primary"
              @click="handleViewDetail(row)">查看详情</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleCancelVote(row)" v-if="canCancelVote(row)">取消投票</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination" v-if="total > 0">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserVotes',
  data() {
    return {
      voteList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    this.fetchUserVotes()
  },
  methods: {
    async fetchUserVotes() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          userId: this.userId
        }
        const res = await this.$http.get('/votes/user', { params })
        if (res.data.code === 1) {
          this.voteList = res.data.data.records
          this.total = res.data.data.total
        } else {
          this.$message.error('获取投票记录失败')
        }
      } catch (error) {
        console.error('获取投票记录失败', error)
        this.$message.error('获取投票记录失败')
      } finally {
        this.loading = false
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchUserVotes()
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    handleViewDetail(row) {
      this.$router.push(`/detail/${row.photoId}`)
    },
    canCancelVote(row) {
      // 判断投票时间是否在24小时内，只有24小时内的投票可以取消
      if (!row.voteTime) return false
      const voteTime = new Date(row.voteTime).getTime()
      const now = new Date().getTime()
      const diffHours = (now - voteTime) / (1000 * 60 * 60)
      return diffHours <= 24
    },
    handleCancelVote(row) {
      this.$confirm('确认取消此投票吗？取消后将不再对作品评分', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await this.$http.delete(`/votes/${row.id}`)
          if (res.data.code === 1) {
            this.$message.success('取消投票成功')
            this.fetchUserVotes()
          } else {
            this.$message.error(res.data.msg || '取消失败')
          }
        } catch (error) {
          console.error('取消投票失败', error)
          this.$message.error('取消失败')
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.empty-block {
  margin: 40px 0;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.photo-title {
  color: #409EFF;
  text-decoration: none;
}

.photo-title:hover {
  text-decoration: underline;
}
</style> 